/*
	This file is part of AVRCppLib.

    AVRCppLib is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AVRCppLib is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AVRCppLib.  If not, see <http://www.gnu.org/licenses/>.

    Copyright (C) Maxime Lemonnier 2007-2011
 */

#include "StringBuffer.h"

StringBuffer::StringBuffer(size_t size, char errorSentinel) : Queue<char>(size, errorSentinel)
{
	// TODO Auto-generated constructor stub

}

StringBuffer::~StringBuffer()
{
	// TODO Auto-generated destructor stub
}

char * StringBuffer::operator >>(char * & lhs) const
{
	if (isEmpty())
	{
		lhs[0] = '\0';
	}
	else
	{
		lhs = new char[count + 1]; // TODO : use realloc

		if(frontIndex <= tailIndex)
		{
			memcpy(lhs, &memory[frontIndex], count);
		}
		else //we have wrapped around we must copy it two steps :
		{
			memcpy(lhs, &memory[frontIndex], (size - frontIndex));
			memcpy(& lhs[(size - frontIndex) + 1], memory, tailIndex - 1);
		}
		lhs[count] = '\0';
	}

	return lhs;
}

StringBuffer & StringBuffer::operator <<(const char * rhs)
{
	for(size_t index = 0; index < strlen(rhs) + 1; index++)
		this->enQueue((char&)rhs[index]);

	return *this;
}


StringBuffer & StringBuffer::operator <<(const char rhs)
{
	this->enQueue((char&)rhs);

	return *this;
}

StringBuffer & StringBuffer::operator <<(const prog_mem * rhs)
{
	const char * dup = strdup(rhs, Allocators::STACK);

	*this << dup;

	return *this;
}

StringBuffer & StringBuffer::operator <<(const Buffer<char> & rhs)
{
	return (StringBuffer &)Queue<char>::operator <<(rhs);
}

StringBuffer & StringBuffer::operator <<(StringBuffer & rhs)
{
	for(size_t index = 0; index < rhs.numberOfElements(); index++)
		this->enQueue((char&)rhs[index]);

	return *this;
}

